# encoding:utf-8
import RPi.GPIO as GPIO
import time

# Vcc_Pin = 33
Echo_Pin = 5
Trig_Pin = 3


def initDist():
    # GPIO.setup(Vcc_Pin, GPIO.OUT, initial=GPIO.HIGH)
    GPIO.setup(Trig_Pin, GPIO.OUT, initial=GPIO.LOW)
    GPIO.setup(Echo_Pin, GPIO.IN)


def _getDist():
    time.sleep(0.1)
    GPIO.output(Trig_Pin, GPIO.HIGH)
    time.sleep(0.00002)  # 这里延时了20us，只要大于10us即可
    GPIO.output(Trig_Pin, GPIO.LOW)
    while GPIO.input(Echo_Pin) == GPIO.LOW:  # 等待Echo脚为高电平
        pass
    # print("echo gpio is high")
    t = time.time()  # 开始计数
    while GPIO.input(Echo_Pin) == GPIO.HIGH:  # 等待Echo脚为低电平
        pass
    # print("echo gpio is low")
    t = time.time() - t  # 计数停止
    # print(t,"s passed")
    if t <= 0:
        print("Can't get distance")
        return -1
    return t * 340 / 2  # 返回距离（m为单位


def getDist():
    dist = []
    print("measuring")
    for i in range(0, 5):
        temp = _getDist()
        if not temp == -1:
            dist.append(temp)
    sum = 0
    for i in dist:
        sum += i
    return sum / len(dist)


if __name__ == '__main__':
    GPIO.setmode(GPIO.BOARD)
    initDist()
    str = "you can input q to quit,or press other key to get a distance"
    r = input(str)
    try:
        while not r == 'q':
            print(getDist() * 100, "cm")
            time.sleep(1)  # 延时1s
            r = input(str)
    except KeyboardInterrupt:
        pass
    GPIO.cleanup()
